import socket
import threading


# 定义处理客户端连接的函数
def handle_client(client_socket, client_address):
    print(f"Accepted connection from {client_address}")
    try:
        while True:
            # 接收客户端发送的数据
            data = client_socket.recv(1024)
            if not data:
                break
            print(f"Received data from {client_address}: {data.decode()}")
            # 发送响应数据给客户端
            client_socket.send(data)
    finally:
        # 关闭客户端连接
        client_socket.close()
        print(f"Connection with {client_address} closed")


def server_run(ipaddr='localhost', listenPort=10000):
    # 创建TCP/IP套接字
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)


    # 绑定套接字到地址和端口
    server_address = (ipaddr, listenPort)
    server_socket.bind(server_address)

    # 监听传入的连接
    server_socket.listen(5)
    print(f"Starting up on {server_address[0]} port {server_address[1]}")

    try:
        while True:
            # 等待一个新的连接
            print("Waiting for a connection...")
            client_socket, client_address = server_socket.accept()

            # 创建一个新的线程来处理连接
            client_thread = threading.Thread(target=handle_client, args=(client_socket, client_address))
            client_thread.start()
    except KeyboardInterrupt:
        print("Server is shutting down.")
    finally:
        # 关闭服务器套接字
        server_socket.close()


server_start(ipaddr='localhost', listenPort=10000)